package com.foreknow.service.impl;

import com.foreknow.bean.User;
import com.foreknow.dao.UserDao;
import com.foreknow.dao.impl.UserDaoImpl;
import com.foreknow.db.DBManager;
import com.foreknow.service.UserService;

import java.sql.Connection;
import java.sql.SQLException;

public class UserServiceImpl implements UserService {
    private UserDao userDao;

    @Override
    public boolean addUser(User user) {
        DBManager dbManager = DBManager.getInstance();
        Connection conn = dbManager.getConnection();
        UserDaoImpl userDao = new UserDaoImpl();
        userDao.setConnection(conn);
        boolean isRigth = false;
        try {
            isRigth = userDao.save(user);
            //提交事务
            conn.commit();
        } catch (SQLException e) {
            e.printStackTrace();
            try {
                //回滚事务
                conn.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }

        return isRigth;//调用UserDao中的方法
    }

    public static void main(String[] args) {
        UserServiceImpl userService = new UserServiceImpl();
        User u;
        u = userService.isValidate("yamaha","999999");
        System.out.println(u.getAdminId()+" "+u.getAdminName()+" "+u.getPassword());

//        User user = new User();
//        user.setAdminName("yamaha");
//        user.setPassword("999999");
//        userService.addUser(user);
    }

    @Override
    public User isValidate(String adminname, String password) {
        DBManager dbManager = DBManager.getInstance();
        Connection conn = dbManager.getConnection();
        UserDaoImpl userDao = new UserDaoImpl();
        userDao.setConnection(conn);
        User user = new User();
        try {
            user = userDao.join(adminname,password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return user;
    }
}
